<?php
/*
 * 优惠券
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\Session;
use app\common\model\Coupon as CouponModel;

class Coupon extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function lists()
    {
        $param = $this->request->param();
        if (!empty($param['title'])) {
            $where = function ($query) use ($param){$query->where('name','LIKE', '%'.trim($param['title']).'%');};
        }else{
           $where = 1;
        }
        $list = CouponModel::where($where)->paginate();
        return $this->fetch('index',['list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['start_time'] = strtotime($param['start_time']);//开始时间
            $param['end_time'] = strtotime($param['end_time']);//结束时间
            $param['surplus'] = $param['stock'];//剩余数量==发放数量
            $result = CouponModel::create($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了优惠券');
            $this->success('添加成功');
        }
        return $this->fetch('save',['sup'=>Db::table('supplier')->where('status',1)->select()]);
    }

    public function edit()
    {
        $id = input('id');
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (isset($param['start_time']) || isset($param['end_time'])) {
                $param['start_time'] = strtotime($param['start_time']);//开始时间
                $param['end_time'] = strtotime($param['end_time']);//结束时间
            }
            $result = CouponModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了优惠券');
            $this->success('修改成功');
        }
        return $this->fetch('save', ['data' => Db::table('coupon')->where('id',$id)->find(),'sup'=>Db::table('supplier')->where('status',1)->select()]);
    }
    //补仓
    public function supply()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $surplus = abs($param['surplus']);
            $result = CouponModel::where('id',$param['id'])->Inc('stock',$surplus)->Inc('surplus',$surplus)->update();
            !$result && $this->error($this->errorMsg);
            insert_admin_log('优惠券补仓');
            $this->success('补仓成功');
        }
        return $this->fetch('supply', ['data' => Db::table('coupon')->find(input('id')),'sup'=>Db::table('supplier')->where('status',1)->select()]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            CouponModel::destroy($param['id']);
            insert_admin_log('删除了优惠券');
            $this->success('删除成功');
        }
    }



}
